package net.whg.datasource;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.util.Properties;

/**
 * 读写分离数据源切换插件
 */
@Intercepts({
        @Signature(type = Executor.class,method = "update",args = {MappedStatement.class,Object.class}),
        @Signature(type = Executor.class,method = "query",args = {MappedStatement.class,Object.class,org.apache.ibatis.session.RowBounds.class,org.apache.ibatis.session.ResultHandler.class})})
public class DynamicDataSourcePlugin implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //拿到当前方法(update,query)所有参数
        Object[] args = invocation.getArgs();
        //拿到第一个参数
        MappedStatement ms = (MappedStatement) args[0];
        //查询走从库
        if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)){
            DynamicDataSource.name.set(DataSourceType.SLAVE);
        }else {
            //增删改走主库
            DynamicDataSource.name.set(DataSourceType.MASTER);
        }
        return invocation.proceed();
    }


    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor){
            return Plugin.wrap(target,this);
        }else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}
